/**
 * Created by wtfssd on 2017/9/13.
 */

import {Actions, ActionConst} from 'react-native-router-flux'

import {AsyncStorage} from 'react-native'
import * as request from '../utils/request'
import {Toast} from 'antd-mobile'
import {ERROR_MSG_DURATION} from '../utils/constant'
import {totalInCart, chuck, countInCart} from '../utils/tools'
import Alipay from 'react-native-wtfssd-alipay'
import * as WeChat from 'react-native-wechat';


console.log(WeChat);
const STORAGE_KEY = "STORAGE_KEY_CART";
const mode = {
    namespace: 'cart',
    state: {
        loading: false,
        list: [],
        total: 0.0,
        count: 0,
        coupon: null,
        marketList: [],
        selectMarket: null,
    },
    reducers: {
        save(state, {payload}) {
            return {...state, ...payload}
        }
    },

    effects: {

        //添加到购物车
        * add({payload}, {call, put, select}) {
            const auth = yield select(state => state.auth);
            if (!auth.isSignIn) {
                yield call(Actions.auth);
                return;
            }
            const data = yield call(request.post, request.API.cartAdd, {...payload, user_id: auth.profile.member_id});
            if (!data || typeof data === 'undefined') return;
            const cart = yield select(state => state.cart);
            const {count, product_id, store_id} = payload;
            /**
             *
             * @param store_id
             * @param product_id
             * @return {*} product
             */
            const pickProduct = (store_id, product_id) => {
                let temp = null;
                if (!cart.list || cart.list.length <= 0) return temp;
                cart.list.map((shop) => {
                    if (shop.id === store_id) {
                        if (Array.isArray(shop.sub)) {
                            shop.sub.map((product) => {
                                if (product.id === product_id) {
                                    product.pivot.count += count;
                                    temp = product;
                                }
                            })
                        }
                    }
                });
                return temp;
            };

            // if (pickProduct(store_id, product_id)) {
            //     yield put({
            //         type: 'save',
            //         payload: {...cart}
            //     })
            // }
            yield put({
                type: 'fetchMarketList',
                payload
            });

            Toast.success(data.data, ERROR_MSG_DURATION);

        },
        //删除商品
        * delete({payload}, {call, put, select}) {
            yield put({
                type: 'save',
                payload: {loading: true}
            });

            const cart = yield select(state => state.cart);

            const data = yield call(request.post, request.API.cartDelete, payload);
            yield put({
                type: 'save',
                payload: {loading: false}
            });

            if (!data || typeof data === 'undefined') return;
            Toast.success('删除成功!', ERROR_MSG_DURATION);
            if (cart.list.length === 1) {
                yield put({
                    type: 'fetchMarketList',
                    payload
                })
            } else {
                yield put({
                    type: 'fetchList',
                    payload: {...payload}
                });
            }
        },
        //获取列表
        * fetchList({payload}, {call, put, select}) {
            const auth = yield select(state => state.auth);
            if (!auth.isSignIn) {
                return;
            }
            yield put({
                type: 'save',
                payload: {loading: true}
            });
            const data = yield call(request.post, request.API.cartList, {...payload, user_id: auth.profile.member_id});
            yield put({
                type: 'save',
                payload: {loading: false}
            });
            if (!data || typeof data === 'undefined') return;
            let list = data.data;
            if (!Array.isArray(list)) {
                let temp = [];
                Object.keys(list).map((k) => {
                    temp.push(list[k]);
                });
                list = temp;
            }
            yield put({
                type: 'save',
                payload: {list, total: totalInCart(list), count: countInCart(list)}
            });
        },

        * pay({payload}, {call, put}) {

            const data = yield call(request.post, request.API.createOrder, payload);
            if (!data || typeof data === 'undefined') return;
            console.log('支付订单 参数', data);

            let order_number = data.data.original.data.out_trade_no;
            order_number = Number(order_number);
            let status = false;
            if (payload.payment === 1) {
                const res = yield call(Alipay.pay, data.data.original.data.alipay);
                console.log('创建订单', data);
                const resultStatus = res.resultStatus;

                if (resultStatus !== '9000') {
                    Toast.fail('支付失败!', ERROR_MSG_DURATION);
                } else {
                    status = true;
                    Toast.success('支付成功!', ERROR_MSG_DURATION);
                    const params = {order_number, status, user_id: payload.user_id, ...payload};
                    console.log('发送支付状态参数', params);
                    const _res = yield call(request.post, request.API.orderPayStatus, params);
                    console.log('发送支付状态', _res);
                    yield put({
                        type: 'fetchList',
                        payload: {...payload},
                    })
                }
            } else {
                let wxPayConfig = data.data.original.data;
                if (wxPayConfig && wxPayConfig.appid) {
                    WeChat.registerApp(wxPayConfig.appid);
                    let payParams = {
                        partnerId: wxPayConfig.partnerid,
                        prepayId: wxPayConfig.prepayid,
                        nonceStr: wxPayConfig.noncestr,
                        timeStamp: wxPayConfig.timestamp,
                        package: wxPayConfig.package,
                        sign: wxPayConfig.sign,
                    };
                    try {
                        const payRes = yield call(WeChat.pay, payParams);
                        status = true;
                        Toast.success('支付成功!', ERROR_MSG_DURATION);
                        const params = {order_number, status, user_id: payload.user_id, ...payload};
                        console.log('发送支付状态参数', params);
                        const _res = yield call(request.post, request.API.orderPayStatus, params);
                        console.log('发送支付状态', _res);
                        yield put({
                            type: 'fetchList',
                            payload: {...payload},
                        })

                    } catch (e) {
                        if (e.message === -1) {
                            status = false;
                            Toast.success('支付失败!', ERROR_MSG_DURATION);
                            const params = {order_number, status, user_id: payload.user_id, ...payload};
                            console.log('发送支付状态参数', params);
                            const _res = yield call(request.post, request.API.orderPayStatus, params);
                            console.log('发送支付状态', _res);
                            yield put({
                                type: 'fetchList',
                                payload: {...payload},
                            })
                        } else {
                            status = false;
                            Toast.success('支付失败!', ERROR_MSG_DURATION);
                            const params = {order_number, status, user_id: payload.user_id, ...payload};
                            console.log('发送支付状态参数', params);
                            const _res = yield call(request.post, request.API.orderPayStatus, params);
                            console.log('发送支付状态', _res);
                            yield put({
                                type: 'fetchList',
                                payload: {...payload},
                            })
                        }
                    }

                }
            }


        },

        * fetchCoupon({payload}, {call, put, select}) {
            const auth = yield select(state => state.auth);
            const data = yield call(request.get, request.API.freeFreight, {user_id: auth.profile.member_id});
            if (data && typeof data !== 'undefined') {
                if (Array.isArray(data.data) && data.data.length > 0) {
                    yield put({
                        type: 'save',
                        payload: {
                            coupon: data.data[0]
                        }
                    })
                }
            }
        },


        //购物车农贸市场列表
        * fetchMarketList({payload}, {call, select, put}) {
            const auth = yield select(state => state.auth);
            const data = yield call(request.get, request.API.carMarketList, {user_id: auth.profile.member_id, ...payload});

            const cart = yield select(state => state.cart);


            const checkSelectMarket = (selectMarket, list) => {
                let temp = null;
                if (!selectMarket) return temp;
                list.map((item) => {
                    if (Number(item.id) === Number(selectMarket.id)) {
                        temp = selectMarket;
                    }
                });
                return temp;
            };
            if (Array.isArray(data.data)) {

                let list = [];
                list = data.data.map(item => ({...item, label: item.name, value: item.id, children: []}));
                let selectMarket = checkSelectMarket(cart.selectMarket, list);
                if (!selectMarket) selectMarket = list[0];
                yield put({
                    type: 'save',
                    payload: {
                        marketList: list,
                        selectMarket
                    }
                });
                if (list.length > 0) {
                    yield put({
                        type: 'fetchList',
                        payload: {markets_id: selectMarket.id}
                    })
                }

            }
            else if (typeof data.data === 'object') {
                let list = [];
                Object.keys(data.data).map(k => {
                    list.push({
                        ...data.data[k],
                        label: data.data[k].name,
                        value: data.data[k].id,
                    })
                });

                let selectMarket = checkSelectMarket(cart.selectMarket, list);
                if (!selectMarket) selectMarket = list[0];
                yield put({
                    type: 'save',
                    payload: {
                        marketList: list,
                        selectMarket
                    }
                });
                if (list.length > 0) {
                    yield put({
                        type: 'fetchList',
                        payload: {markets_id: selectMarket.id}
                    })
                }
            }
        },

        //更改选中农贸市场
        * changeSelectedMarket({payload}, {call, select, put}) {
            const cart = yield select(state => state.cart);
            let selectMarket = null;
            cart.marketList.map((item) => {
                if (Number(item.id) === Number(payload.market_id)) {
                    selectMarket = item;
                }
            });
            yield put({
                type: 'save',
                payload: {selectMarket}
            });
            yield put({
                type: 'fetchList',
                payload: {markets_id: selectMarket.id}
            })
        },

        //保存信息到本地存储
        * saveUserToStorage({payload}, {call}) {
            yield call(AsyncStorage.setItem, STORAGE_KEY, JSON.stringify(payload))
        },

        //从本地存储中恢复信息
        * restoreUserFromStorage({payload}, {call, put}) {
            const data = yield call(AsyncStorage.getItem, STORAGE_KEY);
        },

        * clear({payload}, {put}) {
            yield put({
                list: []
            })
        }
    },

    subscriptions: {
        setup({dispatch}) {
            dispatch({
                type: 'save',
                payload: {
                    list: []
                }
            })
        }
    },
};

export default mode